package com.wmyg.antifake.oauth;

import com.wmyg.antifake.entity.BkUser;
import com.wmyg.antifake.entity.Permission;
import com.wmyg.antifake.entity.Role;
import com.wmyg.antifake.repository.BkUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author 王卓逸
 * @program 前后端分离版妙码后台
 * @description oauth2用户加载服务
 * @create 2019-04-16
 */
@Slf4j
@Component
public class SysUserDetailService implements UserDetailsService {

    @Autowired
    BkUserRepository bkUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BkUser bkUser = bkUserRepository.findByUsername(username);
        if (null == bkUser) {
            throw new UsernameNotFoundException("the user doesn`t exist");
        }
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Role role : bkUser.getRoles()) {
            for (Permission permission : role.getPermissions()) {
                if (null != permission.getUri() && !("".equals(permission.getUri())) && permission.getStatus() == 0) {
                    log.info("find the authority {}", permission.getUri());
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUri());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
        }

        User user = new User(username, bkUser.getPassword(), grantedAuthorities);
        return user;
    }

}
